package highscore;

import java.io.IOException; 
import java.io.File; 
import java.util.Iterator; 
import java.util.Map.Entry;

import configuration.Configuration;

public class FileHighScoreDatabase extends HighScoreDatabase{
	
	public SimpleWriteRead fileSaver = new SimpleWriteRead(); 
	public File ticTacToeHighScores = new File(Configuration.HIGH_SCORE_FILE); 
	public int score;
	public String playerName; 
	public String name;  
	
	public HighScore retrieveHighScore() {
			if(ticTacToeHighScores.exists()){ 
				try{
					return read();
				} catch(IOException e) { 
					throw new IllegalStateException("Error during HighScore reading!");
				}
		} else {
			return new HighScore();
		}
	}
	
	public void write(HighScore highScore) throws IOException { 
		String fileEntry = "";
		if(highScore.getMap().isEmpty()){
			System.out.println("Sorry, there are no High Scores to write. The databse is empty"); 
			return; 
		}
		Iterator<Entry<String, Integer>> it = highScore.getMap().entrySet().iterator(); 
		while(it.hasNext()){
			StringBuilder stringBuilder = new StringBuilder(); 
			Entry<String, Integer> entry = it.next(); 
			fileEntry = "" + stringBuilder.append(it); 
			fileEntry = fileEntry + stringBuilder.append(entry.getKey() + ":" + entry.getValue()+"/n").toString();
		}
		SimpleWriteRead.setContents(ticTacToeHighScores, fileEntry); 
	}
	
	
	private HighScore read() throws IOException { 
		String files = SimpleWriteRead.getContents(ticTacToeHighScores);
		System.out.println("High Score List:" + files); 
		int end = files.length(); 
		HighScore h = new HighScore(); 
		Character start = files.charAt(0); 
		for(int j = 0; j < end; j++){
			Character spot = files.charAt(j); 
			Character spotplus = files.charAt(j+1); 
			if(spot.equals(":")){
				String name = files.substring(start, spot-1); 
				start = files.charAt(spotplus); 
				spotplus = files.charAt(start+1); 
				if(Character.isLetter(spotplus)){
					String scoreinfo = files.substring(start, spotplus-1); 
					int score = Integer.parseInt(scoreinfo); 
					h.addScore(name, score); 
				}
			}
		}
		return h; 
	}
}

  
